package qeug.shsh.opplugin;

import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.fi.bcm.fel.common.NumberUtil;
import org.jetbrains.annotations.NotNull;
import qeug.shsh.bpm.Factory.ThirdServiceFactory;
import qeug.shsh.bpm.service.IG6Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

//费控单据审核后推送G6：推送单据：费用报销单，差旅报销单，借款单，付款申请单，资金计划和资金计划调整的月度支出计划、月度收入计划
public class FcVoucherG6AuditOp extends AbstractOperationServicePlugIn {


    static String oBill = null;

    /*    @Override
        public void registerListener(EventObject e) {
            super.registerListener(e);
            this.addItemClickListeners("tbmain");//监听按钮
        }

        public void beforeItemClick(BeforeItemClickEvent evt) {
            super.beforeItemClick(evt);
            Set<Long> setIds = getSelectOrderIds(this.getSelectedRows());
            if (evt.getItemKey().equals("qeug_pushg6")) {
                if (setIds.size() == 0) {
                    this.getView().showTipNotification("请选择要执行的数据。");
                    return;
                }
                for (Long id : setIds) {
                    getSomeMethod(id);
                }
            }
        }

            public void getSomeMethod(Object id) {
            try {*/
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();//审核通过的单据
        for (DynamicObject bill1 : dataEntities) {
            Object id = bill1.get("id");
            DynamicObject bill = getBillType((Long) id);
            String state = bill.getString("billstatus");//单据状态
            String number = bill.getString("billno");//单据编码
            if ("qeug_fundplan".equals(oBill) || "qeug_fundadjust".equals(oBill)) {
                //资金计划和资金计划调整
                if (!"C".equals(state)) {
                    throw new RuntimeException(number + "审核通过的单据才能推送至G6！");
                }
                DynamicObjectCollection entryEntityCollection = bill.getDynamicObjectCollection("entryentity");//分录
                for (int i = 0; i < entryEntityCollection.size(); i++) {
                    DynamicObject entryEntity = entryEntityCollection.get(i);
                    boolean qeug_isg6 = entryEntity.getBoolean("qeug_isg6");//是否已推送G6
                    if (qeug_isg6) {
                        throw new RuntimeException(number + "第" + (i + 1) + "行数据已推送至G6！");
                    }
                }
            } else {
                if (!"E".equals(state)) {
                    throw new RuntimeException(number + "审核通过的单据才能推送至G6！");
                }
                boolean qeug_istog6 = bill.getBoolean("qeug_istog6");//是否传至G6
                if (qeug_istog6) {
                    throw new RuntimeException(number + "该单据已推送至G6！");
                }
            }
            IG6Service g6Service = null;
            try {
                g6Service = ThirdServiceFactory.createG6Service();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            if ("er_tripreimbursebill".equals(oBill)) {//差旅报销
                g6Service.payForTravel(bill);
            } else if ("er_dailyreimbursebill".equals(oBill)) {//费用报销单付款
                DynamicObjectCollection writeoffmoneyCollection = bill.getDynamicObjectCollection("writeoffmoney");//冲借款
                DynamicObjectCollection accountentryCollection = bill.getDynamicObjectCollection("accountentry");//收款信息
                DynamicObject accountentry = accountentryCollection.get(0);
                BigDecimal orireceiveamount = accountentry.getBigDecimal("orireceiveamount");//收款金额
                if (writeoffmoneyCollection.size() > 0 || orireceiveamount.compareTo(BigDecimal.ZERO) == 0) {
                    return;
                }
                g6Service.payForexpense(bill);
            } else if ("er_dailyloanbill".equals(oBill)) {//借款单
                g6Service.payForDailyLoan(bill);
            } else if ("qeug_fundplan".equals(oBill) || "qeug_fundadjust".equals(oBill)) {//资金计划和资金计划调整-月度支出计划，月度收入计划
                g6Service.payFundPlan(bill);
            } else if ("er_publicreimbursebill".equals(oBill)) {//付款申请单
                int a = 0;
                DynamicObjectCollection expenseEntryEntity = bill.getDynamicObjectCollection("expenseentryentity");//费用明细分录
                for (DynamicObject expenseEntry : expenseEntryEntity) {
                    DynamicObject expenseType = expenseEntry.getDynamicObject("qeug_expensetype");//费用类型
                    String expenseTypeNumber = expenseType.getString("number");
                    if (expenseTypeNumber.equals("FYXM0048")) {
                        //费用类型为税金
                        a++;
                    }
                }
                DynamicObject qeug_refbillfield = bill.getDynamicObject("qeug_refbillfield");//关联预付
                String paymentType = bill.getString("qeug_paytype");//付款类别
                if (qeug_refbillfield != null && a == 0 && "1".equals(paymentType)) {
                    //存在关联预付且不为税金单据且付款类别为应付时，不推送G6，但需自动生成凭证
                    bill.set("head_paydate", new Date());//付款日期，方便后续生成凭证
                    bill.set("billstatus", "G");//直接变为已付款状态
                    SaveServiceHelper.saveOperate("save", "er_publicreimbursebill", new DynamicObject[]{bill}, OperateOption.create());
                    OperateOption saveOption = OperateOption.create();
                    saveOption.setVariableValue("ignoreValidation", String.valueOf(true));//绕过网络互斥操作
                    String id1 = String.valueOf(bill.get("id"));
                    OperationServiceHelper.executeOperate("generatevoucher", "er_publicreimbursebill", new Object[]{id1}, saveOption);//调用生成凭证操作
                    return;
                }
                if (a == 0) {
                    //当费用明细中没有存在税金的时候，推送G6
                    g6Service.paymentApplication(bill);
                } else {
                    //当不为税金单据的时候给是否为税金单据字段赋值true
                    DynamicObject costCompany = bill.getDynamicObject("costcompany");//费用承担公司
                    QFilter[] qFilte = new QFilter[]{new QFilter("group.number", "=", "TAX_ACCOUNT").and("qeug_company.id", "=", costCompany.get("id"))};
                    DynamicObject TAX_ACCOUNT = BusinessDataServiceHelper.loadSingle("bos_assistantdata_detail", qFilte);//税金对应银行存款科目
                    if (TAX_ACCOUNT != null) {
                        String number1 = TAX_ACCOUNT.getString("number");//银行编码
                        QFilter[] qFilte1 = new QFilter[]{new QFilter("bankaccountnumber", "=", number1)};
                        DynamicObject am_accountbank = BusinessDataServiceHelper.loadSingle("am_accountbank", "id", qFilte1);//账户查询
                        if (am_accountbank != null) {
                            bill.set("qeug_bank_acc_salary1", am_accountbank);//银行账号
                        }
                        String qeug_account = TAX_ACCOUNT.getString("qeug_account");//总账科目
                        QFilter[] a1 = new QFilter[]{new QFilter("number", "=", qeug_account)};
                        DynamicObject bd_accountview = BusinessDataServiceHelper.loadSingle("bd_accountview", "id", a1);//会计科目
                        if (bd_accountview != null) {
                            bill.set("qeug_acct_ppe1", bd_accountview);//银行科目
                        }
                    }
                    bill.set("qeug_istax", true);//是否为税金单据
                    bill.set("head_paydate", new Date());//付款日期，方便后续生成凭证
                    bill.set("billstatus", "G");//直接变为已付款状态
                    SaveServiceHelper.saveOperate("save", "er_publicreimbursebill", new DynamicObject[]{bill}, OperateOption.create());
                    OperateOption saveOption = OperateOption.create();
                    saveOption.setVariableValue("ignoreValidation", String.valueOf(true));//绕过网络互斥操作
                    String id1 = String.valueOf(bill.get("id"));
                    OperationServiceHelper.executeOperate("generatevoucher", "er_publicreimbursebill", new Object[]{id1}, saveOption);//调用生成凭证操作
                    return;
                }
            }
        }
    }

    public static DynamicObject getBillType(Long id) {
        oBill = "er_dailyreimbursebill";//费用报销单
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(oBill, new QFilter("id", "=", id).toArray());
        if (dynamicObject == null) {
            dynamicObject = BusinessDataServiceHelper.loadSingle("er_dailyloanbill", new QFilter("id", "=", id).toArray());
            oBill = "er_dailyloanbill";//借款单
        }
        if (dynamicObject == null) {
            dynamicObject = BusinessDataServiceHelper.loadSingle("er_tripreimbursebill", new QFilter("id", "=", id).toArray());
            oBill = "er_tripreimbursebill";//差旅报销单
        }
        if (dynamicObject == null) {
            dynamicObject = BusinessDataServiceHelper.loadSingle("er_publicreimbursebill", new QFilter("id", "=", id).toArray());
            oBill = "er_publicreimbursebill";//付款申请单
        }
        if (dynamicObject == null) {
            dynamicObject = BusinessDataServiceHelper.loadSingle("qeug_fundplan", new QFilter("id", "=", id).toArray());
            oBill = "qeug_fundplan";//资金计划
        }
        if (dynamicObject == null) {
            dynamicObject = BusinessDataServiceHelper.loadSingle("qeug_fundadjust", new QFilter("id", "=", id).toArray());
            oBill = "qeug_fundadjust";//资金计划调整
        }
        return dynamicObject;
    }

    @NotNull
    private Set<Long> getSelectOrderIds(@NotNull ListSelectedRowCollection selectedRows) {
        Set<Long> setIds = new HashSet<>();
        for (ListSelectedRow selectedRow : selectedRows) {
            setIds.add(NumberUtil.toLong(selectedRow.getPrimaryKeyValue()));
        }
        return setIds;
    }
}
